package com.demo.swingquickticket.swing.view.account;

import com.demo.swingquickticket.entity.JsonResult;
import com.demo.swingquickticket.service.AccountService;
import com.demo.swingquickticket.service.DataService;
import com.demo.swingquickticket.swing.layoutUtil.WindowUtil;
import com.demo.swingquickticket.util.SpringUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.swing.*;
import java.awt.*;

@Data
@EqualsAndHashCode(callSuper = true)
public class AccountDialog extends JDialog {

    private static final AccountDialog INSTANCE = new AccountDialog(new JFrame());

    private AccountService accountService = SpringUtils.getBean("accountService");

    private JButton loginAndLogOutBtn;
    private CardLayout cardLayout;
    private JPanel userPanel;

    private AccountDialog(JFrame frame) {
        super(frame);
        init();
        bind();
    }

    public static void getInstance() {
        INSTANCE.setVisible(true);
    }

    private void init() {
        this.setTitle("账号管理");
        this.setSize(WindowUtil.getWindowWidth() / 2, WindowUtil.getWindowHeight() / 2);
        this.getContentPane().setLayout(new BorderLayout(5,5));

        userPanel = new JPanel();
        cardLayout = new CardLayout(5, 5);
        userPanel.setLayout(cardLayout);

        userPanel.add("login", new LoginPanel());
        userPanel.add("detail", new AccountPanel());
        cardLayout.show(userPanel, "login");
//        cardLayout.show(userPanel, "detail");

        loginAndLogOutBtn = new JButton("登入");

        this.getContentPane().add(userPanel, BorderLayout.CENTER);
        this.getContentPane().add(loginAndLogOutBtn, BorderLayout.SOUTH);
    }

    private void bind() {
        loginAndLogOutBtn.addActionListener(e -> {
            if (loginAndLogOutBtn.getText().equals("登入")) {
                JsonResult result = accountService.picLogin(DataService.getAccount().getTemp().get("uuid"));
                if (JsonResult.SUCCESS_CODE.equals(result.getCode())) {
                    JOptionPane.showMessageDialog(INSTANCE, "登入成功");
                    DataService.saveAccount();
                    cardLayout.show(userPanel, "detail");
                    loginAndLogOutBtn.setText("登出");
                } else {
                    JOptionPane.showMessageDialog(INSTANCE, result.getMessage());
                }
            } else {
                DataService.getAccount().clear();
                cardLayout.show(userPanel, "login");
                loginAndLogOutBtn.setText("登入");
            }
        });
    }

}
